# multiAgents.py
# --------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
# http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).


from util import manhattanDistance
from game import Directions
import random, util

from game import Agent

class ReflexAgent(Agent):
    """
      A reflex agent chooses an action at each choice point by examining
      its alternatives via a state evaluation function.

      The code below is provided as a guide.  You are welcome to change
      it in any way you see fit, so long as you don't touch our method
      headers.
    """


    def getAction(self, gameState):
        """
        You do not need to change this method, but you're welcome to.

        getAction chooses among the best options according to the evaluation function.

        Just like in the previous project, getAction takes a GameState and returns
        some Directions.X for some X in the set {North, South, West, East, Stop}
        """
        # Collect legal moves and successor states
        legalMoves = gameState.getLegalActions()

        # Choose one of the best actions
        scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
        bestScore = max(scores)
        bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
        chosenIndex = random.choice(bestIndices) # Pick randomly among the best

        "Add more of your code here if you want to"

        return legalMoves[chosenIndex]

    def evaluationFunction(self, currentGameState, action):
        """
        Design a better evaluation function here.

        The evaluation function takes in the current and proposed successor
        GameStates (pacman.py) and returns a number, where higher numbers are better.

        The code below extracts some useful information from the state, like the
        remaining food (newFood) and Pacman position after moving (newPos).
        newScaredTimes holds the number of moves that each ghost will remain
        scared because of Pacman having eaten a power pellet.

        Print out these variables to see what you're getting, then combine them
        to create a masterful evaluation function.
        """
        # Useful information you can extract from a GameState (pacman.py)
        successorGameState = currentGameState.generatePacmanSuccessor(action)
        newPos = successorGameState.getPacmanPosition()
        newFood = successorGameState.getFood()
        newGhostStates = successorGameState.getGhostStates()
        newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]

        "*** YOUR CODE HERE ***"
        return successorGameState.getScore()

def scoreEvaluationFunction(currentGameState):
    """
      This default evaluation function just returns the score of the state.
      The score is the same one displayed in the Pacman GUI.

      This evaluation function is meant for use with adversarial search agents
      (not reflex agents).
    """
    return currentGameState.getScore()

class MultiAgentSearchAgent(Agent):
    """
      This class provides some common elements to all of your
      multi-agent searchers.  Any methods defined here will be available
      to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.

      You *do not* need to make any changes here, but you can if you want to
      add functionality to all your adversarial search agents.  Please do not
      remove anything, however.

      Note: this is an abstract class: one that should not be instantiated.  It's
      only partially specified, and designed to be extended.  Agent (game.py)
      is another abstract class.
    """

    def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
        self.index = 0 # Pacman is always agent index 0
        self.evaluationFunction = util.lookup(evalFn, globals())
        self.depth = int(depth)
        self.n_agents = 0

class MinimaxAgent(MultiAgentSearchAgent):
    """
      Your minimax agent (question 1)
    """
    def minimax(self,state,agent,depth):
        score = 0

        #if done for this entire layer update, reset agent to 0
        if agent == self.n_agents:
            agent = 0 #the agent points now to the pacman

        #if done return the value
        if depth == (self.depth*self.n_agents) or state.isWin() or state.isLose():
            return self.evaluationFunction(state)

        #get the max value if agent, otherwise get min value for ghost
        if agent == 0:
            score = -9999
            for action in state.getLegalActions(agent):
                score = max(score,self.minimax(state.generateSuccessor(agent,action),agent+1,depth+1))
        else:
            score = 9999
            for action in state.getLegalActions(agent):
                score = min(score,self.minimax(state.generateSuccessor(agent,action),agent+1,depth+1))
        return score

    def getAction(self, gameState):
        """
          Returns the minimax action from the current gameState using self.depth
          and self.evaluationFunction.

          Here are some method calls that might be useful when implementing minimax.

          gameState.getLegalActions(agentIndex):
            Returns a list of legal actions for an agent
            agentIndex=0 means Pacman, ghosts are >= 1

          gameState.generateSuccessor(agentIndex, action):
            Returns the successor game state after an agent takes an action

          gameState.getNumAgents():
            Returns the total number of agents in the game
        """
        #needed so we can check if we are done with a layer
        self.n_agents = gameState.getNumAgents()

        actionlist = {}

        #get legal actions for the pacman, consider each action using minimax
        #once done return the action that would yield the best results
        actions = gameState.getLegalActions(0)
        for i in actions:
            score = self.minimax(gameState.generateSuccessor(0,i),1,1)
            actionlist[score] = i
        return actionlist[max(actionlist)]


class AlphaBetaAgent(MultiAgentSearchAgent):
    """
      Your minimax agent with alpha-beta pruning (question 2)
    """

    def getAction(self, gameState):
        """
          Returns the minimax action using self.depth and self.evaluationFunction
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()

class ExpectimaxAgent(MultiAgentSearchAgent):
    """
      Your expectimax agent (optional)
    """

    '''
        Student notes:
            this is just the minimax agent copied from the code above
            the only difference is that it uses betterEvaluationFunction

            The code of the minimax will not be commented because the comments
            were added later.
            The extensive comments will be added at Class MinimaxAgent()

    '''
    def minimax(self,state,agent,depth):
        score = 0

        #if done for this entire layer update
        if agent == self.n_agents:
            agent = 0

        #if done return the value
        if depth == (self.depth*self.n_agents) or state.isWin() or state.isLose():
            return betterEvaluationFunction(state)

        #get the max value if agent, otherwise get min value for ghost
        if agent == 0:
            score = -9999
            for action in state.getLegalActions(agent):
                score = max(score,self.minimax(state.generateSuccessor(agent,action),agent+1,depth+1))
        else:
            score = 9999
            for action in state.getLegalActions(agent):
                score = min(score,self.minimax(state.generateSuccessor(agent,action),agent+1,depth+1))
        return score

    def getAction(self, gameState):
        """
          Returns the expectimax action using self.depth and self.evaluationFunction

          All ghosts should be modeled as choosing uniformly at random from their
          legal moves.
        """
        actionlist = {}
        self.n_agents = gameState.getNumAgents()
        actions = gameState.getLegalActions(0)
        for i in actions:
            score = self.minimax(gameState.generateSuccessor(0,i),1,1)
            actionlist[score] = i
        return actionlist[max(actionlist)]

    #util.raiseNotDefined()

def betterEvaluationFunction(currentGameState):
    """
    Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
    evaluation function (optional). (Question 3)

    DESCRIPTION:
        The score gets better if the scaredtimer is active
        The score reduces as the distance to the ghost increases, but
        it doesn't actively hunt down ghosts if they are scared
        because the goal is to eat all food and not hunt
        The distance to the closest food has a influence on the score,
        in the future it should check if the surroundings of that food has more food

        in summary the score depends on:
            -scared timer
            -minimum distance to ghost
            -minimum distance to food
            -vanilla getScore() function
    """
    score = 0

    pacman = currentGameState.getPacmanPosition()

    #get the distances to the ghosts in perspect to the pacman, store in list
    ghost_dist = []
    ghost_states = currentGameState.getGhostStates()
    for gs in ghost_states:
        ghost_dist += [manhattanDistance(pacman, gs.getPosition())]

    #get the distances to the food in perspect to the pacman, store in list
    distances = []
    foods = currentGameState.getFood().asList()
    for f in foods:
        distances += [manhattanDistance(pacman,f)]

    #invert the value of the lowest dist so it can reflect the score
    inv = 0
    if len(distances) > 0:
        inv = 1.0/(min(distances))

    #add scores if scared time is active
    t_scared = [i.scaredTimer for i in ghost_states]
    for t in t_scared:
        score += t

    #calculate final score
    score += (min(ghost_dist))*(inv)+(currentGameState.getScore())
    return score

# Abbreviation
better = betterEvaluationFunction

class ContestAgent(MultiAgentSearchAgent):
    """
      Your agent for the mini-contest
    """

    def getAction(self, gameState):
        """
          Returns an action.  You can use any method you want and search to any depth you want.
          Just remember that the mini-contest is timed, so you have to trade off speed and computation.

          Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually
          just make a beeline straight towards Pacman (or away from him if they're scared!)
        """
        "*** YOUR CODE HERE ***"
        util.raiseNotDefined()

